﻿using System;
using System.Linq;
using System.Reflection;
using ClosedXML.Excel;
using SuppKids.Core.Reporting.Data;

namespace SuppKids.Core.Reporting.Excel
{
	public class SkladDailyReportGenerator : ExcelReportGenerator
	{
		protected override void CreateWorkbook(out XLWorkbook workbook, out IXLWorksheet worksheet)
		{
			workbook = new XLWorkbook(Assembly.GetExecutingAssembly().GetManifestResourceStream("SuppKids.Core.Reporting.Excel.Templates.SkladDailyReportTemplate.xlsx"));
			worksheet = workbook.Worksheets.FirstOrDefault() ?? workbook.Worksheets.Add(workbook.Worksheets.Count.ToString(this.FormatProvider));
		}

		protected override void CreateContent(IXLWorksheet worksheet, IReportData reportData)
		{
			var data = reportData as SkladDailyReportData;
			if (data == null)
			{
				throw new InvalidOperationException("Report data is not valid for this kind of report.");
			}

            string ReportDate = data.ReportDate.Day.ToString() + "." + data.ReportDate.Month.ToString() + "." + data.ReportDate.Year.ToString();
            worksheet.Cell("A1").Value = "Отчет за " + ReportDate;


			var index = 4;

			var items = data.ProductsAtStorage.OrderBy(a => a.DeliveryDate).ToArray();
			var balance = 0d;
			foreach (var result in items)
			{
				balance += result.Balance;
				worksheet.Cell(string.Format("A{0}", index)).Value = result.Product.Name;
				worksheet.Cell(string.Format("B{0}", index)).Value = result.DeliveryDate;
				worksheet.Cell(string.Format("C{0}", index)).Value = result.Supplier;
				worksheet.Cell(string.Format("D{0}", index)).Value = result.Recipient;
				worksheet.Cell(string.Format("E{0}", index)).Value = result.Bill;
				worksheet.Cell(string.Format("F{0}", index)).Value = result.DeliveryAmount;
				worksheet.Cell(string.Format("G{0}", index)).Value = result.ConsumptAmount;
				worksheet.Cell(string.Format("H{0}", index)).Value = balance;
                worksheet.Cell(string.Format("I{0}", index)).Value = result.Product.Cipher;
                worksheet.Cell(string.Format("J{0}", index)).Value = index - 3;
				index++;
			}

            worksheet.Column(1).InsertColumnsBefore(1);
            worksheet.Column("K").CopyTo(worksheet.Cell("A1"));
            worksheet.Column("K").Delete();

            var range = worksheet.Range(string.Format("A4:J{0}", (index - 1)));
            range.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
            range.Style.Border.InsideBorder = XLBorderStyleValues.Thin;
            worksheet.Range("A3:J3").Style.Border.OutsideBorder = XLBorderStyleValues.Medium;

		}
	}
}
